package com.epam.facebook_client;

import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.epam.facebook_client.api.API;
import com.epam.facebook_client.content.contract.AppContract;
import com.epam.facebook_client.fragment.HeadFragment;
import com.epam.facebook_client.manager.ImageManager;
import com.epam.facebook_client.processor.AlbumsProcessor;
import common.adapters.AbstractCursorAdapter;
import common.processor.IProcessor;

public class AlbumsActivity extends BaseServiceActivity implements LoaderCallbacks<Cursor> {

	private static final String TAG = AlbumsActivity.class.getSimpleName();

	private ImageManager imageManager;
	private GridView albumGridView;
	private EditText dialogEditText;
	private AlertDialog alertDialog;
	private ProgressBar progressBar;

	private String id;
	private String myId;

	private Map<String, String> parameter;

	private AbstractCursorAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_albums);
		albumGridView = (GridView) findViewById(R.id.grid_albums);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		createDialog();
		Bundle extras = getIntent().getExtras();
		myId = getSharedPreferences(HeadFragment.MY_ID, 0).getString(HeadFragment.ID, null);
		if (extras != null) {
			id = extras.getString("id");
		} else {
			id = myId;
		}
		imageManager = ImageManager.get(this);
		
		albumGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(getApplication(), PhotosActivity.class);
				intent.putExtra("id", id);
				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		getSupportLoaderManager().initLoader(0, null, this);
		parameter = new HashMap<String, String>(2);
		parameter.put(AlbumsProcessor.EXTRA_URL, API.getAlbums(id));
		parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_GET);
		startServiceHelper(parameter, progressBar, AlbumsProcessor.ACTION);
	}

	private void createDialog() {
		AlertDialog.Builder dialogBuilderCreateAlbum = new AlertDialog.Builder(this);
		dialogBuilderCreateAlbum.setTitle(R.string.create_album);
		dialogEditText = new EditText(this);
		dialogBuilderCreateAlbum.setView(dialogEditText);
		dialogBuilderCreateAlbum.setPositiveButton("Create", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				parameter = new HashMap<String, String>(3);
				parameter.put(AlbumsProcessor.EXTRA_URL, API.ALBUMS_POST);
				parameter.put(AlbumsProcessor.EXTRA_NAME, dialogEditText.getText().toString());
				parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_POST);
				startServiceHelper(parameter, progressBar, AlbumsProcessor.ACTION);
			}
		});

		dialogBuilderCreateAlbum.setNegativeButton("Cancel", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		alertDialog = dialogBuilderCreateAlbum.create();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_albums, menu);
		if(id != myId){
			menu.findItem(R.id.menu_create).setVisible(false);
		}
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refresh:
			parameter = new HashMap<String, String>(2);
			parameter.put(AlbumsProcessor.EXTRA_URL, API.getAlbums(id));
			parameter.put(IProcessor.EXTRA_EXECUTE_METHOD, IProcessor.METHOD_DELETE);
			startServiceHelper(parameter, null, AlbumsProcessor.ACTION);
			break;
		case R.id.menu_create:
			alertDialog.show();
			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onServiceResult(int requestId, Intent requestIntent, int resultCode, Bundle resultData) {
		progressBar.setVisibility(View.GONE);
		if (getRequestId() != requestId) {
			return;
		}
		switch (resultCode) {
		case IProcessor.RESULT_OK:
			if(resultData != null){
				if (resultData.getString(AlbumsProcessor.EXTRA_RESPONSE).contains("id")) {
					Toast.makeText(this, "Album created", Toast.LENGTH_SHORT).show();
					recreatedActivity();
				}
			}
			break;
		case IProcessor.RESULT_ERROR:
			Exception e = (Exception) resultData.getSerializable(IProcessor.EXTRAS_ERROR);
			Log.e(TAG, "ERROR: " + e);
			Toast.makeText(this, "ERROR: " + e.getMessage(), Toast.LENGTH_SHORT).show();
			break;
		}
	}

	private void recreatedActivity() {
		Intent i = new Intent(getApplicationContext(), AlbumsActivity.class);
		i.putExtra("id", id);
		startActivity(i);
		finish();
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle extras) {
		String[] selectionArgs = { this.id };
		return new CursorLoader(this, AppContract.AlbumColumns.CONTENT_URI, null, AppContract.AlbumColumns.USER_ID + " = ?", selectionArgs, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		progressBar.setVisibility(View.GONE);
		if (cursor.getCount() > 0) {
			String[] columnNames = { AppContract.AlbumColumns.NAME, AppContract.AlbumColumns.COVER,
					AppContract.AlbumColumns.COUNT };
			int[] viewId = { R.id.album_name, R.id.album_image, R.id.album_count };
			adapter = new AbstractCursorAdapter(this, cursor, imageManager, viewId, columnNames) {

				@Override
				public int getLayoutAdapterId() {
					return R.layout.adapter_album_grid_item;
				}

				@Override
				public void setImageNull(ImageView imageView) {
					imageView.setImageDrawable(null);
				}
			}; 
			albumGridView.setAdapter(adapter);
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {

	}
}
